package user_mgt

import (
	"context"
	"encoding/json"
	"fmt"
	"internal_training_be/db"
	"net/http"
	"time"
)

// HandleLogin 处理登陆请求
func (e *EmployeeImpl) HandleLogin(w http.ResponseWriter, r *http.Request) {
	logger.Info("EmployeeImpl HandleLogin received a request")

	// 设置响应头
	w.Header().Set("Content-Type", "application/json")

	// 解析请求体
	var req LoginRequest
	if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
		logger.Errorf("Error decoding request payload: %v", err)
		http.Error(w, "Invalid request payload", http.StatusBadRequest)
		return
	}

	// 检查用户名和密码是否为空
	if req.Username == "" || req.Password == "" {
		logger.Errorf("Username and password are required")
		http.Error(w, "Username and password are required", http.StatusBadRequest)
		return
	}

	// 获取数据库连接
	dbConn, err := db.GetDBConn()
	if err != nil {
		logger.Errorf("Error getting database connection: %v", err)
		http.Error(w, "Internal server error", http.StatusInternalServerError)
		return
	}
	defer dbConn.Release()

	// 查询数据库，检查用户名和密码是否匹配
	var exists bool
	query := fmt.Sprintf(`
		SELECT EXISTS (
			SELECT 1
			FROM %s.%s
			WHERE username = $1 AND password = $2
		)
	`, schema, employeeTable)
	err = dbConn.QueryRow(context.Background(), query, req.Username, req.Password).Scan(&exists)
	if err != nil {
		logger.Errorf("Error querying database: %v", err)
		http.Error(w, "Internal server error", http.StatusInternalServerError)
		return
	}

	// 构造响应
	resp := LoginResponse{}
	if exists {
		resp.Success = true
		resp.Message = "Login successful"

		// 从数据库获取ID
		var id string
		query = fmt.Sprintf(`
			SELECT id
			FROM %s.%s
			WHERE username = $1 AND password = $2
		`, schema, employeeTable)
		err = dbConn.QueryRow(context.Background(), query, req.Username, req.Password).Scan(&id)
		if err != nil {
			logger.Errorf("Error querying database: %v", err)
			http.Error(w, "Internal server error", http.StatusInternalServerError)
			return
		}

		// 生成 token
		token, err := jwtEmployee.GenerateToken(id)
		if err != nil {
			logger.Errorf("Error generating token: %v", err)
			http.Error(w, "Internal server error", http.StatusInternalServerError)
			return
		}

		// 将 token 设置到 Cookies
		setTokenToCookies(w, token)

		// 设置响应状态码
		w.WriteHeader(http.StatusOK)

		logger.Infof("Employee %s logged in successfully", req.Username)
	} else {
		resp.Success = false
		resp.Message = "Invalid username or password"

		// 设置响应状态码
		w.WriteHeader(http.StatusUnauthorized)

		logger.Infof("Failed login attempt for user: %s", req.Username)
	}

	// 发送 JSON 响应
	if err := json.NewEncoder(w).Encode(resp); err != nil {
		logger.Errorf("Error encoding response: %v", err)
		http.Error(w, "Internal server error", http.StatusInternalServerError)
	}
}

// HandleGetInfo 处理获取员工个人信息
func (e *EmployeeImpl) HandleGetInfo(w http.ResponseWriter, r *http.Request) {
	logger.Infof("EmployeeImpl HandleGetInfo received a request")

	// 设置响应头
	w.Header().Set("Content-Type", "application/json")

	// 获取数据库连接
	dbConn, err := db.GetDBConn()
	if err != nil {
		logger.Errorf("Error getting database connection: %v", err)
		http.Error(w, "Internal server error", http.StatusInternalServerError)
		return
	}
	defer dbConn.Release()

	// 从 context 中获取员工ID
	employeeId, ok := r.Context().Value("employeeId").(string)
	if !ok {
		logger.Errorf("Failed to get employee id from request context")
		http.Error(w, "Failed to get employee id from request context", http.StatusInternalServerError)
		return
	}

	// 从数据库获取员工信息
	var employeeName string
	query := fmt.Sprintf(`
		SELECT username
		FROM %s.%s
		WHERE id = $1
	`, schema, employeeTable)
	err = dbConn.QueryRow(context.Background(), query, employeeId).Scan(&employeeName)
	if err != nil {
		logger.Errorf("Failed to get employee name from db: %v", err)
		http.Error(w, "Failed to get employee name from db", http.StatusInternalServerError)
		return
	}

	// 构造响应
	resp := EmployeeInfoResponse{
		Success: true,
		Message: "Get employee info successfully",
		ID:      employeeId,
		Name:    employeeName,
	}

	// 将响应编码为 JSON 并返回
	if err := json.NewEncoder(w).Encode(resp); err != nil {
		logger.Errorf("Failed to encode response: %v", err)
		http.Error(w, `{"error": "Failed to encode response"}`, http.StatusInternalServerError)
		return
	}

	logger.Infof("Successfully returned employee info for ID: %s", employeeId)
}

// HandleLogin 处理登陆请求
func (e *AdminImpl) HandleLogin(w http.ResponseWriter, r *http.Request) {
	logger.Infof("AdminImpl HandleLogin received a request")

	// 设置响应头
	w.Header().Set("Content-Type", "application/json")

	// 解析请求体
	var req LoginRequest
	if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
		logger.Errorf("Error decoding request payload: %v", err)
		http.Error(w, "Invalid request payload", http.StatusBadRequest)
		return
	}

	// 检查用户名和密码是否为空
	if req.Username == "" || req.Password == "" {
		logger.Errorf("Username and password are required")
		http.Error(w, "Username and password are required", http.StatusBadRequest)
		return
	}

	// 获取数据库连接
	dbConn, err := db.GetDBConn()
	if err != nil {
		logger.Errorf("Error getting database connection: %v", err)
		http.Error(w, "Internal server error", http.StatusInternalServerError)
		return
	}
	defer dbConn.Release()

	// 查询数据库，检查用户名和密码是否匹配
	var exists bool
	query := fmt.Sprintf(`
		SELECT EXISTS (
			SELECT 1
			FROM %s.%s
			WHERE username = $1 AND password = $2
		)
	`, schema, adminTable)
	err = dbConn.QueryRow(context.Background(), query, req.Username, req.Password).Scan(&exists)
	if err != nil {
		logger.Errorf("Error querying database: %v", err)
		http.Error(w, "Internal server error", http.StatusInternalServerError)
		return
	}

	// 构造响应
	resp := LoginResponse{}
	if exists {
		resp.Success = true
		resp.Message = "Login successful"

		// 从数据库获取ID
		var id string
		query = fmt.Sprintf(`
			SELECT id
			FROM %s.%s
			WHERE username = $1 AND password = $2
		`, schema, adminTable)
		err = dbConn.QueryRow(context.Background(), query, req.Username, req.Password).Scan(&id)
		if err != nil {
			logger.Errorf("Error querying database: %v", err)
			http.Error(w, "Internal server error", http.StatusInternalServerError)
			return
		}

		// 生成 token
		token, err := jwtAdmin.GenerateToken(id)
		if err != nil {
			logger.Errorf("Error generating token: %v", err)
			http.Error(w, "Internal server error", http.StatusInternalServerError)
			return
		}

		// 将 token 设置到 Cookies
		setTokenToCookies(w, token)

		// 设置响应状态码
		w.WriteHeader(http.StatusOK)

		logger.Infof("Admin %s logged in successfully", req.Username)
	} else {
		resp.Success = false
		resp.Message = "Invalid username or password"

		// 设置响应状态码
		w.WriteHeader(http.StatusUnauthorized)

		logger.Infof("Failed login attempt for user: %s", req.Username)
	}

	// 发送 JSON 响应
	if err := json.NewEncoder(w).Encode(resp); err != nil {
		logger.Errorf("Error encoding response: %v", err)
		http.Error(w, "Internal server error", http.StatusInternalServerError)
	}
}

// HandleAddCourse 添加课程
func (e *AdminImpl) HandleAddCourse(w http.ResponseWriter, r *http.Request) {
	logger.Infof("AdminImpl HandleAddCourse received a request")

	// 设置响应头
	w.Header().Set("Content-Type", "application/json")

	// 解析请求体
	var req CourseInfo
	if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
		logger.Errorf("Error decoding request payload: %v", err)
		http.Error(w, "Invalid request payload", http.StatusBadRequest)
		return
	}

	// 检查课程信息是否完整
	if req.Name == "" || req.Description == "" || req.Duration == "" {
		logger.Errorf("Course name, description, and duration are required")
		http.Error(w, "Course name, description, and duration are required", http.StatusBadRequest)
		return
	}

	// 从请求的context中获取adminId
	adminId, ok := r.Context().Value("adminId").(string)
	if !ok {
		logger.Errorf("Failed to get admin id from request context")
		http.Error(w, "Failed to get admin id from request context", http.StatusInternalServerError)
		return
	}

	// 生成课程信息
	id := fmt.Sprintf("%d", time.Now().Unix())
	name := req.Name
	description := req.Description
	duration := req.Duration
	status := req.Status
	number := 0 // 报名人数

	// 获取数据库连接
	dbConn, err := db.GetDBConn()
	if err != nil {
		logger.Errorf("Error getting database connection: %v", err)
		http.Error(w, "Internal server error", http.StatusInternalServerError)
		return
	}
	defer dbConn.Release()

	// 将课程信息插入 t_course 表
	query := fmt.Sprintf(`
		INSERT INTO %s.%s (id, name, admin_id, description, number, duration, status)	
		VALUES ($1, $2, $3, $4, $5, $6, $7)
	`, schema, courseTable)
	_, err = dbConn.Exec(context.Background(), query, id, name, adminId, description, number, duration, status)
	if err != nil {
		logger.Errorf("Error inserting course into database: %v", err)
		http.Error(w, "Internal server error", http.StatusInternalServerError)
		return
	}

	// 构造响应
	resp := LoginResponse{
		Success: true,
		Message: "Course added successfully",
	}

	// 设置响应状态码
	w.WriteHeader(http.StatusOK)

	logger.Infof("Course %s added successfully", name)

	// 发送 JSON 响应
	if err := json.NewEncoder(w).Encode(resp); err != nil {
		logger.Errorf("Error encoding response: %v", err)
		http.Error(w, "Internal server error", http.StatusInternalServerError)
	}
}
